import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

from detector import CompleteNetworkDetector

def main():
    detector = CompleteNetworkDetector()
    print("=" * 60)
    print("完整网络黑灰产检测系统")
    print("=" * 60)
    try:
        print("步骤 1/6: 加载数据构建完整图网络...")
        detector.load_and_build_complete_graph('employ.csv', 'policy.csv', 'claim.csv',
                                               'visit.csv', 'institution.csv')
        print("步骤 2/6: 训练完整网络GNN模型...")
        detector.train_complete_model(epochs=80, lr=0.001)
        print("步骤 3/6: 执行网络风险预测...")
        detector.predict_network_risks()
        print("步骤 4/6: 检测完整社区...")
        detector.detect_complete_communities(min_community_size=5)
        print("步骤 5/6: 计算完整社区风险...")
        detector.calculate_community_risk_with_completeness()
        print("步骤 6/6: 生成完整证据链和报告...")
        detector.build_complete_evidence_chains(top_k=15)
        report = detector.generate_complete_report()
        summary = report['summary']
        print("\n" + "=" * 60)
        print("完整网络检测完成!")
        print("=" * 60)
        print(f"发现社区: {summary['total_communities']} 个")
        print(f"高风险: {summary['high_risk_communities']} 个 (阈值: {summary['risk_threshold_high']:.3f})")
        print(f"中风险: {summary['medium_risk_communities']} 个 (阈值: {summary['risk_threshold_medium']:.3f})")
        print(f"完整高风险网络: {summary['complete_high_risk_networks']} 个")
        print(f"阈值差异: {summary['threshold_difference']:.3f}")
        print(f"分析节点: {summary['total_nodes_analyzed']} 个")
        print(f"分析边数: {summary['total_edges_analyzed']} 条")
        print(f"关键节点类型: {', '.join(summary['key_node_types'])}")
        risk_dist = report.get('risk_distribution', {})
        if risk_dist:
            print(f"\n风险分布 (完整网络):")
            print(f"  风险范围: [{risk_dist.get('risk_min', 0):.3f}, {risk_dist.get('risk_max', 0):.3f}]")
            print(f"  风险均值: {risk_dist.get('risk_mean', 0):.3f}")
            print(f"  完整性均值: {risk_dist.get('completeness_mean', 0):.3f}")
            print(f"  完整网络比例: {risk_dist.get('complete_network_ratio', 0):.1%}")
        completeness_analysis = report.get('network_completeness_analysis', {})
        if completeness_analysis:
            print(f"\n网络完整性分析:")
            for key, value in completeness_analysis.items():
                print(f"  {key}: {value:.3f}")
        if detector.is_trained:
            model_path, scaler_path = detector.save_model()
            print(f"\n模型文件:")
            print(f"  模型参数: {model_path}")
            print(f"  特征处理器: {scaler_path}")
        recommendations = report.get('recommendations', [])
        if recommendations:
            print(f"\n处置建议 (基于完整网络):")
            for i, rec in enumerate(recommendations, 1):
                print(f"  {i}. {rec}")
        return detector, report
    except Exception as e:
        logger.error(f"检测过程失败: {e}")
        raise

if __name__ == "__main__":
    detector, report = main()